package net.java.mediasystems.web;

import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import javax.faces.context.FacesContext;

/**
 * Message Provider
 */
public final class MessageProvider {
	
	private static final String RESOURCEBUNDLE_VARIABLE_NAME = "messages";
	
	private MessageProvider() {
		
	}
	
	/**
	 * Get translated Message from the ResourceBundle by given Message-Key.
	 *  
	 * @param key String
	 * @return String
	 */
	public static String getMessage(String key) {
		return getMessage(key, (Object[]) null);
	}
	
	/**
	 * Get translated Message with substituted params from the ResourceBundle by given Message-Key.
	 * 
	 * @param key String
	 * @param params Object...
	 * @return String
	 */
	public static String getMessage(String key, Object... params) {
		FacesContext facesContext = FacesContext.getCurrentInstance();
		ResourceBundle resourceBundle = facesContext.getApplication().getResourceBundle(facesContext, RESOURCEBUNDLE_VARIABLE_NAME);
		
		String result = null;
		try {
			result = resourceBundle.getString(key);
		} catch (MissingResourceException missingResourceException) {
			result = "???" + key + "???";
		}
		
		if (params != null) {
			MessageFormat mf = new MessageFormat(result, facesContext.getViewRoot().getLocale());
			result = mf.format(params, new StringBuffer(), null).toString();
		}
		
		return result;
	}
}
